﻿package kit4j.ui.cs.swing.component;

import java.awt.Component;
import java.awt.Font;

import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.ListCellRenderer;

/**
 * 字体列表的单元格绘制组件，实现以对应的字体显示出字体名字的单元格。<br />
 * 特别的，如果对应的字体不支持显示字体名称，单元格将使用字体列表使用的字体显示名称。
 * 
 * @author MiniKnife
 * 
 */
public class JFontListCellRenderer extends JLabel implements ListCellRenderer {

	private static final long serialVersionUID = 1L;

	public JFontListCellRenderer() {
		super();
	}

	@Override
	public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected,
			boolean cellHasFocus) {
		if (value != null) {
			Font listFont = list.getFont();
			Font f = (Font) value;
			f = f.deriveFont(listFont.getStyle(), listFont.getSize());

			setText(f.getName());
			if (f.canDisplayUpTo(f.getName()) == -1) {
				setFont(f);
			} else {
				setFont(list.getFont());
			}
		}

		if (isSelected) {
			setBackground(list.getSelectionBackground());
			setForeground(list.getSelectionForeground());
		} else {
			setBackground(list.getBackground());
			setForeground(list.getForeground());
		}
		setEnabled(list.isEnabled());
		setOpaque(true);

		return this;
	}
}
